package cn.seaboot.commons.ftp.pool;

import cn.seaboot.commons.exception.ServiceException;
import cn.seaboot.commons.ftp.FtpSource;
import cn.seaboot.commons.ftp.FtpException;
import cn.seaboot.commons.ftp.FtpProperties;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

/**
 * FTP 连接池
 *
 * @author Mr.css
 * @version 2021-03-12 9:30
 */
public class FTPClientPool implements AutoCloseable {
    private final GenericObjectPool<FTPClient> pool;

    /**
     * constructor
     *
     * @param factory    连接池工厂
     * @param properties 连接池配置
     */
    public FTPClientPool(final BasePooledObjectFactory<FTPClient> factory, FtpProperties properties) {
        GenericObjectPoolConfig<FTPClient> objectPoolConfig = new GenericObjectPoolConfig<>();
        objectPoolConfig.setMaxTotal(properties.getMaxTotal());
        this.pool = new GenericObjectPool<>(factory, objectPoolConfig);
    }

    /**
     * 对外借出一个FtpClient，方法与{@link #returnFTPClient}对应，用完的FtpClient需要归还到连接池中，
     *
     * @return -
     * @throws ServiceException - {@link FtpSource#createFTPClient()} )}
     */
    public FTPClient borrowFTPClient() {
        try {
            return pool.borrowObject();
        } catch (Exception e) {
            throw new FtpException(e);
        }
    }

    /**
     * 归还一个FtpClient，方法与{@link #borrowFTPClient()}对应，用完的FtpClient需要归还到连接池中
     *
     * @param ftpClient -
     */
    public void returnFTPClient(FTPClient ftpClient) {
        pool.returnObject(ftpClient);
    }

    /**
     * 销毁全部链接
     */
    @Override
    public void close() {
        pool.close();
    }
}
